'use client';
import PageTitle from '@/components/admin/common/PageTitle';
import Loading from '@/components/common/Loading';
import React, { useEffect, useState, Suspense, useCallback } from 'react';
import Pagination from '@/components/admin/common/Pagination';
import { useSearchParams, useRouter } from 'next/navigation';
import message from '@/components/common/message';
import request from '@/utils/request';
import CollectionsItem from '@/components/admin/collections/CollectionsItem';
import { ROUTE_COLLECTIONS } from '@/config/settings'

function CollectionsContent() {
  const [loaded, setLoaded] = useState(false);
  const [collections, setCollections] = useState([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [limit, setLimit] = useState(16);
  const [addCollectionValue] = useState({ title: '新集合', description: '新集合内容' });
  const router = useRouter();
  const searchParams = useSearchParams();

  useEffect(() => {
    const pageParam = searchParams.get('page');
    if (!pageParam) {
      const params = new URLSearchParams(searchParams);
      params.set('page', '1');
      router.replace(`?${params.toString()}`);
    } else {
      const pageNum = parseInt(pageParam, 10);
      setPage(isNaN(pageNum) || pageNum < 1 ? 1 : pageNum);
    }
  }, [searchParams, router]);

  const editHandle = (id) => {
    if (!id) {
      message.error('页面 ID 不存在');
      return;
    }
    router.push(`${ROUTE_COLLECTIONS}/${id}`);
  };

  const fetchCollections = useCallback(async () => {
    try {
      const res = await request(`/api/admin/collections?limit=${limit}&page=${page}`);
      if (res.code !== 0) {
        message.error(res.codeMap[res.code] || '获取集合失败');
        return;
      }
      setTotal(res.total);
      setCollections(res.data);
      setLoaded(true);
    } catch (error) {
      message.error('获取集合分类失败，请稍后重试');
      console.error('获取集合分类失败:', error);
    }
  }, [limit, page]);

  useEffect(() => {
    fetchCollections();
    return () => {
      setLoaded(false);
    };
  }, [page, limit, fetchCollections]);

  const handleCopy = (e, slug) => {
    e.stopPropagation();
    if (!slug) {
      message.error('当前Slug未配置，不能生成链接');
      return;
    }
    navigator.clipboard.writeText(`/collections/${slug}`).then(() => {
      message.success('页面链接已复制到剪贴板');
    }).catch(err => {
      console.error('Failed to copy:', err);
      message.error('复制链接失败，请手动复制');
    });
  }

  const handleDelete = async (e, id) => {
    e.stopPropagation();
    if (!window.confirm('确定要删除该集合分类吗？')) return;
    if (!id) {
      message.error('页面 ID 不存在');
      return;
    }
    try {
      const res = await request(`/api/admin/collections`, { method: 'DELETE', body: JSON.stringify({ id: Number(id) }) });
      if (res.code === 0) {
        message.success('页面删除成功');
        fetchCollections();
      } else {
        message.error(res.codeMap[res.code]);
      }
    }
    catch (error) {
      console.error('Failed to delete page:', error);
      message.error('删除页面失败，请稍后再试');
    }
  }

  const addHandle = () => {
    message.success('产品分类添加中，请稍等...');
    request(`/api/admin/collections`, { method: 'POST', body: JSON.stringify(addCollectionValue) })
      .then(res => {
        if (res.code === 0) {
          message.success('产品分类添加成功');
          router.push(`${ROUTE_COLLECTIONS}/${res.id}`);
        } else {
          message.error(res.codeMap[res.code] || '产品分类添加失败');
        }
      })
  }

  const handlePageChange = (newPage) => {
    const params = new URLSearchParams(searchParams);
    params.set('page', newPage.toString());
    router.push(`?${params.toString()}`);
  };

  const handleSend = (e, slug, status) => {
    e.stopPropagation();
    if (status !== 0) {
      message.error('当前分类未启用，页面无法打开');
      return;
    }
    if (!slug) {
      message.error('当前Slug未配置，不能生成链接');
      return;
    } else {
      window.open(`${window ? window.origin : process.env.NEXT_PUBLIC_BASE_URL}/collections/${slug}`, '_blank', 'noopener,noreferrer');
    }
  }

  const content = (
    <div>
      <PageTitle title="产品分类" buttonText={'新建分类'} onButtonClick={addHandle} />
      <div>
        <div className='grid grid-cols-4 gap-4 p-4 items-center bg-white sticky top-12 z-1 rounded-t-xs border-b border-gray-200 text-[#333333] font-semibold text-xs'>
          <div>标题</div>
          <div>状态</div>
          <div>创建时间</div>
          <div className='text-right pr-6'>功能配置</div>
        </div>
        <div className='content bg-white rounded-b-sm'>
          {collections.length > 0 ? (collections.map(item => (<CollectionsItem value={item} key={item.id} onEdit={editHandle} onCopy={handleCopy} onDelete={handleDelete} onSend={handleSend} />))) : <div className="text-center">暂无数据</div>}
        </div>
      </div>
      <Pagination total={total} page={page} limit={limit} leftDisabled={page === 1} leftOnClick={() => { if (page > 1) handlePageChange(page - 1) }} rightDisabled={page === Math.ceil(total / limit)} rightOnClick={() => { if (page < Math.ceil(total / limit)) handlePageChange(page + 1) }} />
    </div>
  )

  return (
    <div>
      {loaded ? content : <Loading />}
    </div>
  )
}

export default function Collections() {
  return (
    <Suspense fallback={<div>加载中...</div>}>
      <CollectionsContent />
    </Suspense>
  )
}